package com.cash.app.ui.order

import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.cash.app.R
import com.cash.app.base.BaseActivity
import com.cash.app.custom.AppActionBar
import com.cash.app.databinding.AcLoanListBinding
import com.cash.app.ui.order.adapter.LoanListAdapter
import com.cash.app.utils.addVerticalSpacing
import com.cash.app.utils.hide
import com.cash.app.utils.visible

class LoanListActivity : BaseActivity() {

    private lateinit var binding: AcLoanListBinding
    private val viewModel: LoanListViewModel by viewModels()
    private lateinit var adapter: LoanListAdapter

    override fun setViewBind() {
        binding = AcLoanListBinding.inflate(layoutInflater)
    }

    override fun getLayoutView(): View {
        return binding.root
    }

    override fun getAppActionBar(): AppActionBar? {
        return binding.actionBar
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setupRecyclerView()
        setupEmptyState()
        setupObservers()
        setupSwipeRefresh()
        viewModel.getLoanList()
    }

    private fun setupSwipeRefresh() {
        binding.swipeRefreshLayout.setColorSchemeResources(
            R.color.app_theme_color,
        )
        binding.swipeRefreshLayout.setOnRefreshListener {
            binding.swipeRefreshLayout.isRefreshing = true
            viewModel.getLoanList()
        }
    }

    private fun setupRecyclerView() {
        adapter = LoanListAdapter()
        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(this@LoanListActivity)
            adapter = this@LoanListActivity.adapter
            addVerticalSpacing(resources.getDimensionPixelSize(R.dimen.home_list_item_spacing))
        }

        adapter.onItemClickListener = { item ->
            LoanInfoActivity.start(this, item.o_id)
        }
    }

    private fun setupEmptyState() {
        binding.emptyState.apply {
            setEmptyText(getString(R.string.loan_data_empty_tip))
            setEmptyImage(R.mipmap.home_data_empty)
        }
    }

    private fun setupObservers() {
        viewModel.loanData.observe(this) { data ->
            adapter.setData(data.order_list)
            binding.swipeRefreshLayout.isRefreshing = false
        }
        viewModel.showEmptyState.observe(this) { showEmpty ->
            if (showEmpty) {
                binding.emptyState.visible()
                binding.recyclerView.hide()
            } else {
                binding.emptyState.hide()
                binding.recyclerView.visible()
            }
            binding.swipeRefreshLayout.isRefreshing = false
        }
    }
} 